<!DOCTYPE html>
<html lang="zh-CN">

  <head>
    <meta charset="UTF-8">
    <title>知题 - 随便写的小刷题工具</title>
    <style>
      :root {
        --primary-color: #2c3e50;
        --secondary-color: #3498db;
        --background-color: #f5f6fa;
      }

      body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        margin: 0;
        padding: 20px;
        background-color: var(--background-color);
        min-height: 100vh;
      }

      .container {
        display: grid;
        grid-template-columns: 250px 1fr;
        gap: 20px;
        max-width: 1200px;
        margin: 0 auto;
      }

      .header {
        grid-column: 1 / -1;
        margin-bottom: 20px;
        border-bottom: 2px solid var(--primary-color);
        padding-bottom: 10px;
      }

      .brand {
        font-size: 24px;
        color: var(--primary-color);
        font-weight: bold;
        text-decoration: none;
      }

      .sidebar {
        background: white;
        padding: 20px;
        padding-top: 0px;
        padding-bottom: 0px;
        border-radius: 10px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      }

      .file-list {
        list-style: none;
        padding: 0;
        margin: 10px 0;
        max-height: 400px;
        overflow-y: auto;
      }

      .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px;
        margin: 5px 0;
        background: #f8f9fa;
        border-radius: 4px;
        transition: 0.2s;
      }

      .file-item:hover {
        background: #e9ecef;
      }

      .main-content {
        background: white;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      }

      .upload-section {
        border: 2px dashed #ccc;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
      }

      .question-card {
        position: relative;
        min-height: 200px;
        padding: 20px;
        border-radius: 8px;
        margin: 15px 0;
        border: 1px solid #eee;
      }

      .controls {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        margin-top: 20px;
      }

      .answer {
        color: #28a745;
        font-weight: bold;
        margin-top: 15px;
      }

      button {
        background: var(--secondary-color);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        transition: 0.3s;
      }

      button:hover {
        opacity: 0.9;
        transform: translateY(-1px);
      }

      .danger {
        background: #e74c3c;
      }

      .footer {
        grid-column: 1 / -1;
        text-align: center;
        margin-top: 0px;
        color: #666;
        font-size: 0.9em;
      }

      /* 提示信息样式 */
      #noDataMessage {
        display: none;
        color: #666;
        text-align: center;
        padding: 40px 20px;
        font-size: 16px;
        line-height: 1.6;
      }

      .has-questions #questionContent {
        display: block !important;
      }

      .no-questions #noDataMessage {
        display: block !important;
      }

      .no-questions #questionContent {
        display: none !important;
      }

      .help-section {
        grid-column: 1 / -1;
        margin: 0 0 20px;
      }

      .help-card {
        background: #e3f2fd;
        border: 1px solid #2196f3;
        border-radius: 10px;
        padding: 15px;
        display: flex;
        gap: 15px;
      }

      .help-icon {
        font-size: 32px;
        flex-shrink: 0;
      }

      .help-content h3 {
        margin: 0 0 10px;
        color: #1976d2;
      }

      .help-content ol {
        margin: 0 0 10px;
        padding-left: 20px;
      }

      .help-content li {
        margin: 8px 0;
        line-height: 1.5;
      }

      .tips {
        background: rgba(255, 255, 255, 0.8);
        padding: 10px;
        border-radius: 6px;
        font-family: monospace;
        display: flex;
        flex-direction: column;
        gap: 4px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <div class="header">
        <a href="#" class="brand">知题 - 随便写的小刷题工具</a>
      </div>

      <div class="help-section">
        <div class="help-card">
          <div class="help-icon">📘</div>
          <div class="help-content">
            <h3>使用指南</h3>
            <ol>
              <li>如果是 Word 文档，请将内容<em>复制到普通TXT文件</em>后上传</li>
              <li>点击 <em>选择文件</em> 上传符合格式的TXT文件（数据将<em>永久存储</em>在浏览器中）</li>
              <li>点击文件名右侧的 <em>×</em> 可删除文件</li>
              <li>勾选左侧文件开始刷题（支持多选）</li>
            </ol>
            <div class="tips">
              <strong>文件格式示例：</strong>
              <span>1.题目内容...</span>
              <span>A.选项1</span>
              <span>B.选项2</span>
              <span>答案：A</span>
            </div>
          </div>
        </div>
      </div>

      <div class="sidebar">
        <h3>题目库管理</h3>
        <div class="upload-section">
          <input type="file" id="fileInput" accept=".txt">
          <p>上传规范格式的题目文件</p>
        </div>

        <div class="controls">
          <button onclick="selectAllFiles()">全选</button>
          <button class="danger" onclick="clearAllFiles()">清空全部</button>
        </div>

        <ul class="file-list" id="fileList"></ul>
      </div>

      <div class="main-content">
        <div id="quizPanel" class="hidden">
          <div class="question-card">
            <div id="noDataMessage">📚 当前没有可用题目或未选中题目，请先上传文件或选中题目文件</div>
            <div id="questionContent">
              <div id="questionText"></div>
              <div class="options" id="options"></div>
              <div class="answer" id="answer"></div>
            </div>
          </div>

          <div class="controls">
            <button onclick="toggleMode()" id="modeBtn">顺序模式</button>
            <button onclick="prevQuestion()">上一题</button>
            <button onclick="showAnswer()">显示答案</button>
            <button onclick="nextQuestion()">下一题</button>
          </div>
        </div>
      </div>

      <div class="footer">
        <p>开发者：罗文彬 | 联系方式：15132605871/Wenbin.Lo@outlook.com</p>
        <p>版本：1.0.0 | 更新日期：2025-3-15</p>
      </div>
    </div>

    <script>
      let currentQuestions = [];
      let currentIndex = 0;
      let isRandom = false;
      let originalOrder = [];

      class StorageManager {
        static STORAGE_KEY = 'zhiti-data';
        static SELECTED_KEY = 'zhiti-selected';

        static getStorage() {
          return JSON.parse(localStorage.getItem(this.STORAGE_KEY) || '{}');
        }

        static saveFile(filename, data) {
          try {
            const storage = this.getStorage();
            storage[filename] = data;
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(storage));
            return true;
          } catch (e) {
            if (e.name === 'QuotaExceededError') {
              alert('存储空间不足，请删除部分旧题目');
              return false;
            }
          }
        }

        static deleteFile(filename) {
          const storage = this.getStorage();
          delete storage[filename];
          localStorage.setItem(this.STORAGE_KEY, JSON.stringify(storage));
        }

        static clearAll() {
          localStorage.removeItem(this.STORAGE_KEY);
        }

        static saveSelectedFiles(filenames) {
          localStorage.setItem(this.SELECTED_KEY, JSON.stringify(filenames));
        }

        static getSelectedFiles() {
          return JSON.parse(localStorage.getItem(this.SELECTED_KEY) || []);
        }
      }

      function parseContent(text) {
        const errors = [];
        const validQuestions = [];
        const rawQuestions = text.split(/\n\s*\n+/).filter(q => q.trim() !== '');

        rawQuestions.forEach((q, index) => {
          try {
            const lines = q.trim().split('\n').filter(l => l.trim() !== '');
            if (lines.length < 3) throw new Error('题目格式不完整 缺少必要内容（至少需要题目、选项和答案）');

            const answerLine = lines.find(l => l.startsWith('答案：'));
            if (!answerLine) throw new Error('缺少答案行');

            validQuestions.push({
              number: (index + 1).toString(),
              text: lines[0].split('.').slice(1).join('.').trim(),
              options: lines.slice(1, -1).filter(l => /^[A-D]\./.test(l)),
              answer: answerLine.split('：')[1].trim()
            });
          } catch (e) {
            errors.push(`第 ${index + 1} 题: ${e.message}`);
          }
        });

        if (errors.length > 0) {
          alert(`发现 ${errors.length} 处解析错误：\n${errors.slice(0, 3).join('\n')}${errors.length > 3 ? '\n...' : ''}`);
        }
        return validQuestions;
      }

      function renderFileList() {
        const selectedFiles = StorageManager.getSelectedFiles();
        const fileList = document.getElementById('fileList');

        fileList.innerHTML = Object.entries(StorageManager.getStorage())
          .map(([filename, data]) => `
                    <li class="file-item">
                        <label>
                            <input type="checkbox" 
                                data-filename="${filename}"
                                ${selectedFiles.includes(filename) ? 'checked' : ''}>
                            ${filename} (${data.length}题)
                        </label>
                        <button class="danger delete-btn" data-filename="${filename}">×</button>
                    </li>
                `).join('');

        // 绑定事件使用事件委托
        fileList.addEventListener('click', (e) => {
          if (e.target.classList.contains('delete-btn')) {
            const filename = e.target.dataset.filename;
            if (confirm(`确认删除 ${filename} 吗？`)) {
              StorageManager.deleteFile(filename);
              renderFileList();
              startQuiz();
            }
          }
        });

        // 复选框变化时自动保存
        fileList.addEventListener('change', (e) => {
          if (e.target.matches('[data-filename]')) {
            const selected = Array.from(document.querySelectorAll('[data-filename]:checked'))
              .map(el => el.dataset.filename);
            StorageManager.saveSelectedFiles(selected);
            startQuiz();
          }
        });
      }

      // 文件上传事件处理
      document.getElementById('fileInput').addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function (e) {
          try {
            const questions = parseContent(e.target.result);
            if (questions.length === 0) throw new Error('未发现有效题目');

            if (StorageManager.saveFile(file.name, questions)) {
              const selected = StorageManager.getSelectedFiles();
              if (!selected.includes(file.name)) {
                selected.push(file.name);
                StorageManager.saveSelectedFiles(selected);
              }
              renderFileList();
              startQuiz();
              alert(`成功导入 ${questions.length} 道题目`);
            }
          } catch (error) {
            alert(`文件导入失败: ${error.message}`);
          }
        };
        reader.readAsText(file, 'UTF-8');
      });

      function startQuiz() {
        const selected = Array.from(document.querySelectorAll('[data-filename]:checked'))
          .map(el => el.dataset.filename);
        StorageManager.saveSelectedFiles(selected);

        currentQuestions = selected.flatMap(filename =>
          StorageManager.getStorage()[filename] || []
        );

        document.getElementById('options').innerHTML = '';
        document.getElementById('answer').innerHTML = '';
        document.getElementById('questionText').innerHTML = '';

        const quizPanel = document.getElementById('quizPanel');
        if (currentQuestions.length === 0) {
          quizPanel.classList.remove('hidden', 'has-questions');
          quizPanel.classList.add('no-questions');
        } else {
          originalOrder = [...currentQuestions];
          quizPanel.classList.remove('hidden', 'no-questions');
          quizPanel.classList.add('has-questions');
          currentIndex = 0;
          renderQuestion();
        }
      }

      function renderQuestion() {
        if (!currentQuestions[currentIndex]) return;

        const q = currentQuestions[currentIndex];
        document.getElementById('questionText').innerHTML =
          `<strong>第${q.number}题:</strong> ${q.text}`;
        document.getElementById('options').innerHTML =
          q.options.map(opt => `<div>${opt}</div>`).join('');
        // 新增：每次渲染题目时自动清空答案
        document.getElementById('answer').innerHTML = '';
      }

      function nextQuestion() {
        currentIndex = (currentIndex + 1) % currentQuestions.length;
        renderQuestion();
      }

      function prevQuestion() {
        currentIndex = (currentIndex - 1 + currentQuestions.length) % currentQuestions.length;
        renderQuestion();
      }

      function showAnswer() {
        document.getElementById('answer').innerHTML =
          `正确答案：${currentQuestions[currentIndex].answer}`;
      }

      function toggleMode() {
        isRandom = !isRandom;
        document.getElementById('modeBtn').textContent = isRandom ? '随机模式' : '顺序模式';
        currentQuestions = isRandom ?
          [...currentQuestions].sort(() => Math.random() - 0.5) :
          [...originalOrder];
        currentIndex = 0;
        renderQuestion();
      }

      function selectAllFiles() {
        document.querySelectorAll('[data-filename]').forEach(checkbox => {
          checkbox.checked = true;
        });
        startQuiz();
      }

      function clearAllFiles() {
        if (confirm('确认清空所有题目吗？')) {
          StorageManager.clearAll();
          currentQuestions = [];
          renderFileList();
          startQuiz();
        }
      }

      // 事件委托处理删除操作
      document.getElementById('fileList').addEventListener('click', (e) => {
        if (e.target.classList.contains('delete-btn')) {
          const filename = e.target.dataset.filename;
          if (confirm(`确认删除 ${filename} 吗？`)) {
            StorageManager.deleteFile(filename);
            renderFileList();
            startQuiz();
          }
        }
      });

      // 初始化
      document.addEventListener('DOMContentLoaded', () => {
        renderFileList();
        startQuiz();
      });
    </script>
  </body>

</html>